/* eslint-disable no-unused-vars */
import {
  setToken,
  removeToken,
  setUserInfo,
  removeUserInfo,
  setPassword,
  setTopNavList,
  setApplicationId
} from '@/utils/auth';
import {loginByUsername, getLeftMenus, getTopMenus} from "@/views/login/login.service";
import store from "@/store";
import {MOCK_ROUTES} from '@/utils/constants';

const state = {
  name: '',
  hasMenu: false,
  codes: [],
  applicationId: '',
  topNavList: ''
};

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MENU: (state, hasMenu) => {
    state.hasMenu = hasMenu
  },
  SET_CODES: (state, codes) => {
    state.codes = codes
  },
  SET_APPLICATIONID: (state, applicationId) => {
    state.applicationId = applicationId
  },
  SET_TOP_NAV_LIST: (state, topNavList) => {
    state.topNavList = topNavList
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      loginByUsername(userInfo.username.trim(), userInfo.password).then(response => {
        commit('SET_NAME', response.data.trueName); // 设置用户名
        setToken(response.data.token); // 设置token
        setUserInfo(response.data);
        setPassword(response.data.isDefaultPwd); // 保存是否为默认密码
        resolve(response);
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取左侧菜单列表
  getLeftMenus({commit, state}) {
    return new Promise((resolve, reject) => {
      getLeftMenus().then(response => {
        // 添加一个role flag 来判断左侧菜单已经拉取完毕，避免每次都会去请求后台
        commit('SET_MENU', true);
        // 测试路由
        // store.commit('permission/SET_ROUTES', MOCK_ROUTES.data);
        const routers = [
          {
            "meta": {"route": "首页", "icon": "el-icon-s-home", "title": "首页"},
            "name": "首页",
            "path": "/dashboard",
            "redirect": "",
            "keyCodes": ["Query"],
            "children": []
          },
          {
            "meta": {"route": "用户信息管理", "icon": "el-icon-user-solid", "title": "用户信息管理"},
            "name": "用户信息管理",
            "path": "/user-list",
            "keyCodes": ["Query", "Create", "Edit", "Delete"],
            "children": []
          }
          // {
          //   "meta": {"route": "字典管理", "icon": "el-icon-s-tools", "title": "字典管理"},
          //   "name": "字典管理",
          //   "path": "/dictionary-list",
          //   "keyCodes": ["Query", "Create", "Edit", "Delete"],
          //   "children": []
          // }
        ];
        store.commit('permission/SET_ROUTES', routers);

        // store.commit('permission/SET_ROUTES', response.data);
        resolve();
      }).catch(error => {
        // 告诉组件加载失败，停止loading
        reject(error);
      });
    });
  },

  // 获取顶部菜单
  getTopMenus({commit, state}) {
    return new Promise((resolve, reject) => {
      getTopMenus().then(response => {
        commit('SET_APPLICATIONID', response.data[0].objectId); // 获取APPLICATIONID
        commit('SET_TOP_NAV_LIST', response.data); // 获取top菜单
        setTopNavList(response.data);
        setApplicationId(response.data[0].objectId);
        resolve();
      }).catch(error => {
        // 告诉组件加载失败，停止loading
        reject(error);
      });
    });
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      commit('SET_MENU', false);
      removeToken();
      removeUserInfo();
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, {root: true})
      resolve();
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_MENU', false);
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
